function updateInterval() {
  var value = get('interval').valueAsNumber;
  get('intervalOut').innerText = value;
  setItem({
    interval: value * 60000 // minutes to millis
  }, function() {
    chrome.extension.getBackgroundPage().updatePolling();
  });
}

function updateBooleanPref(prefName) {
  var value = get(prefName).checked;
  var obj = {};
  obj[prefName] = value;
  setItem(obj);
}

function updateNearbyPref() {
  updateBooleanPref('nearby');
  chrome.extension.getBackgroundPage().prePoll();
}

document.body.onload = function() {
  get('authWarning').onclick = clickAuth;
  get('interval').oninput = updateInterval;
  get('playSound').onclick = playSound;
  get('sound').onchange = function() { updateBooleanPref('sound'); };
  get('comments').onchange = function() { updateBooleanPref('comments'); };
  get('nearby').onchange = updateNearbyPref;
  get('filter').onchange = expandCollapseFilter;
  get('selectAll').onclick = function() { select(true); };
  get('selectNone').onclick = function() { select(false); };
  get('reset').onclick = reset;

  getItem(['interval', 'sound', 'comments', 'nearby', 'token', 'filter'],
    function(settings) {
      get('interval').value = parseInt(settings['interval'] || '900000') / 60000;
      updateInterval();

      // Update checked state for boolean prefs
      updateBooleanPrefUI('sound', settings['sound']);
      updateBooleanPrefUI('comments', settings['comments']);
      updateBooleanPrefUI('nearby', settings['nearby']);

      if (! settings['token']) {
        get('authWarning').style.display = 'block';
      }

      if (settings['filter']) {
        var el = get('filter');
        var onclick = el.onclick;
        el.checked = true;
        el.onclick = onclick;
        expandCollapseFilter();
      }
    });
}

function updateBooleanPrefUI(prefName, value) {
  get(prefName).checked = value;
}

function clickAuth() {
  chrome.extension.getBackgroundPage().startAuth();
  get('authWarning').style.display = 'none';
}

function playSound() {
  new Audio('sounds/ding.wav').play();
}

function reset() {
  if (window.confirm('Are you sure you want to return the ' +
      'extension to its original, fresh-from-the-Web-Store state?')) {
    clearStorage();
    chrome.extension.getBackgroundPage().updatePolling(); // Update polling
    chrome.extension.getBackgroundPage().getMe(); // Re-fetch user's own info
    window.location.reload();
  }
}

function expandCollapseFilter() {
  setItem({
    filter: get('filter').checked
  }, function() {
    getItem('filterFriends', function(settings) {
      var filterFriends = JSON.parse(settings['filterFriends'] || '[]');
      var container = get('filterContainer');
      container.style.display = (container.style.display == 'none') ?
          'block' : 'none';
      xhr('https://api.foursquare.com/v2/users/self/friends', function(resp) {
        var friends = resp['response']['friends']['items'];
        friends.sort(function(a, b) {
          var al = (a['lastName'] || '').toUpperCase();
          var bl = (b['lastName'] || '').toUpperCase();
          if (al < bl) { return -1; }
          else if (al > bl) { return 1; }
          else { return 0; }
        });
        friends.forEach(function(friend) {
          var id = friend['id'];
          var html = '<div class="friend">' +
              '<input type="checkbox" id="' + id + '" onclick="toggle(' + id + ')" />' +
              '<label for="' + id + '">' +
              '<img src="' + friend['photo'] + '" />' +
              (friend['firstName'] || '') + ' ' + (friend['lastName'] || '') +
              '</label>' + 
              '</div>';
          container.innerHTML += html;
        });
        filterFriends.forEach(function(id) { get('' + id).checked = true; });
      });
    });
  });
}

function toggle(id) {
  id = '' + id;

  getItem('filterFriends', function(settings) {
    var filterFriends = JSON.parse(settings['filterFriends'] || '[]');
    var add = get(id).checked;
    if (add) {
      filterFriends.push(id);
    } else { // remove
      filterFriends.splice(filterFriends.indexOf(id), 1);
    }

    setItem({
      filterFriends: filterFriends
    });
  });
}

function select(allNone) {
  var inputs = document.querySelectorAll('div#filterContainer input');
  for (var i = 0; i < inputs.length; i++) {
    inputs[i].checked = allNone;
  }
}